import { useEditorRule } from './config/useEditorRule'
import { useUploadFileRule } from './config/useUploadFileRule'
import { useUploadImgRule } from './config/useUploadImgRule'
import { useUploadImgsRule } from './config/useUploadImgsRule'
import { useDictSelectRule } from './config/useDictSelectRule'
import { useSelectRule } from './config/useSelectRule'
import type { Menu } from './type'
import { apiSelectRule } from './config/selectRule'

export const useFormCreateDesigner = async (designer: Ref) => {
  const editorRule = useEditorRule()
  const uploadFileRule = useUploadFileRule()
  const uploadImgRule = useUploadImgRule()
  const uploadImgsRule = useUploadImgsRule()

  /**
   * 定制表单组件
   */
  const buildFormComponents = () => {
    // 移除上传、富文本组件，使用自定义的文件上传、图片上传、富文本组件替代
    designer.value?.removeMenuItem('upload')
    designer.value?.removeMenuItem('fcEditor')
    const components = [editorRule, uploadFileRule, uploadImgRule, uploadImgsRule]
    components.forEach((component) => {
      // 添加自定义组件规则
      designer.value?.addComponent(component)
      // 将拖拽组件加入到 main 菜单(分组)下
      // 'main' | 'subform' | 'aide' | 'layout'
      designer.value?.appendMenuItem('main', {
        icon: component.icon,
        name: component.name,
        label: component.label
      })
    })
  }

  const dictSelectRule = useDictSelectRule()
  const userSelectRule = useSelectRule({
    name: 'UserSelect',
    label: '用户选择器',
    icon: 'icon-user-o'
  })
  const deptSelectRule = useSelectRule({
    name: 'DeptSelect',
    label: '部门选择器',
    icon: 'icon-address-card-o'
  })
  const apiSelectRule0 = useSelectRule({
    name: 'ApiSelect',
    label: '接口选择器',
    icon: 'icon-server',
    props: [...apiSelectRule]
  })

  /**
   * 定制系统菜单及其表单组件
   */
  const buildSystemMenu = () => {
    const components = [dictSelectRule, userSelectRule, deptSelectRule, apiSelectRule0]
    const menu: Menu = {
      name: 'system',
      title: '系统组件',
      list: components.map((component) => {
        // 插入组件规则
        designer.value?.addComponent(component)
        // 插入拖拽按钮到 `system` 分类下
        return {
          icon: component.icon,
          name: component.name,
          label: component.label
        }
      })
    }
    designer.value?.addMenu(menu)
  }

  // 给调用该useXX函数的组件注册一个mounted监听器(可以注册多个)
  onMounted(async () => {
    await nextTick()
    buildFormComponents()
    buildSystemMenu()
  })
}
